package cn.bkw.ytkapi.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class GlobleExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {

        BKWException bkwex = null;
        String message = "";
        if (e instanceof BKWException) {
            bkwex = (BKWException) e;
            message = bkwex.getMessage();
            int flag = message.indexOf("|"); //不存在为-1,存在则返回 | 所在的位置

            /*处理异地登录*/
            if (!"".equals(message) && message != null && message.length()>0 && flag != -1) {

                if ("40300".equals(message.substring(0, message.indexOf("|")))) {
                    Cookie cookie = new Cookie("errcode", "40300");
                    cookie.setMaxAge(1000);
                    cookie.setPath("/");
                    String str = message.substring(message.indexOf("|") + 1);
                    byte[] bt = new byte[0];
                    try {
                        bt = str.getBytes("utf-8");
                    } catch (UnsupportedEncodingException e1) {
                        e1.printStackTrace();
                    }
                    String msg = "";
                    for (byte b : bt) {
                        msg += b + ",";
                    }
                    Cookie cookie1 = new Cookie("errmsg", msg.substring(0, msg.length() - 1));
                    cookie1.setMaxAge(1000);
                    cookie1.setPath("/");

                    httpServletResponse.addCookie(cookie);
                    httpServletResponse.addCookie(cookie1);
                    return null;

                }else if(message.indexOf("会话超时") != -1){
                    try {
                        PrintWriter out = httpServletResponse.getWriter();
                        out.print("<script type='text/javascript'>");
                        out.print("parent.location.href='login.jsp';");
                        out.print("</script>");

                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }

            }
        } else {
           e.printStackTrace();
        }
       return null;
      /*  //返回错误页面  错误页面暂时未定义
        ModelAndView model = new ModelAndView("error");
        model.addObject("msg", message);
        return model;*/
    }


}
